<?php

App::uses('ChartManager', 'Lib/chart');

class ChartController extends AppController {
    var $helpers = array ('Html','Form','Session');
    var $name = 'Chart'; // riferimento alla cartella delle view
    //var $modelClass = 'Multa';

    // var $components = array('Permission','Acl'); 
    
    public function beforeFilter(){
		if(!$this->request->is('ajax'))
			parent::beforeFilter();
        // $this->Auth->allow('getLog','refreshPermission');
    	$this->loadModel("Chart");
    }

    public function index() {
    	$this->Chart->recursive=1;
		$charts = $this->Chart->find("all");
    	$this->set("charts",$charts);
    }

    public function draw($code) {
		try {
			$this->layout="ajax";
			$this->autorender = false;
	    	$this->Chart->recursive=1;
			$chart = $this->Chart->findByCode($code);
			$cm = new ChartManager($chart);
			$data = $cm->getDatasource();
			$ret=array();
			$ret["success"] = true;
			$ret["type"] = $chart["Chart"]["type"];
			$ret["title"] = $chart["Chart"]["descr"];
			$ret["data"] = $data; 
			echo json_encode($ret);
			die();
		} catch (Exception $e) {
			CakeLog::error($e->getMessage());
			$ret = array('success'=> false,'message'=>$e->getMessage(),'level'=>'error');
			echo json_encode($ret);
            die();
		}
    }

	public function refresh() {
        if($this->request->is('ajax')){
        	try {
		        $this->layout="ajax";
		        $this->autorender = false;
		    	$this->Chart->recursive=1;
				$charts = $this->Chart->find("all");
				$data["success"] = true;
				$data["charts"] = $charts;
				echo json_encode($data);
        	} catch (Exception $e) {
			    CakeLog::error($e->getMessage());
				$data = array('success'=> false,'message'=>$e->getMessage());
				echo json_encode($data);
        	}
			exit();
		} else {
            throw new MethodNotAllowedException(__("Non è possibile accedere al metodo."));
        }
	}


}
?>